'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 登陆服务器
 * @author sundbcn@gmail.com (sun debing)
 */

var async = require('async');
var Code = require('../../../consts/code');
var userModel = require('../../../models/userModel');
var roleModel = require('../../../models/roleModel');
var serverStatusModel = require('../../../models/serverStatusModel');
var authService = require('../../../services/authService');

module.exports = function (app) {
    return new Handler(app);
};

var Handler = function (app) {
    this.app = app;
    this.globalChannelService = app.get('globalChannelService');
};

/**
 * 新用户登陆
 */
Handler.prototype.entry = function (msg, session, next) {
    var signed_key = msg.signed_key;

    if (!signed_key) {
        return next(null, {
            code: Code.ENTRY_TOKEN_EXPIRE
        });
    }

    var auth_uid;
    var channel_id;
    async.waterfall(
        [
            function (cb) {
                serverStatusModel.isGameLocked(cb);
            },
            function (game_locked, cb) {
                console.log('------ game_locked:', game_locked);
                if (game_locked) {
                    // 服务器已锁定(停服维护)
                    return next(null, {
                        code: Code.ENTRY_SERVER_LOCKED
                    });
                }

                // 与账号服务器验证signed_key
                authService.checkSignedKey(signed_key, cb);
            },
            function (uid, chn, cb) {
                auth_uid = uid;
                channel_id = chn;
                _getForbidStatus(auth_uid, cb);
            },
            function (forbid_status, cb) {
                if (!!forbid_status) {
                    return next(null, {
                        code: Code.ENTRY_HAVE_FORBID
                    });
                }

                session.set('auth_uid', auth_uid);
                session.set('channel_id', channel_id);
                session.pushAll(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK
            });
        }
    );
};

/**
 * 获取封停状态
 */
var _getForbidStatus = function (auth_uid, cb) {
    userModel.getByUid(auth_uid, function (err, model) {
        if (!!err) {
            return cb(err);
        }
        cb(null, model.isForbid());
    });
};

/**
 * 锁定服务器
 */
Handler.prototype.lockServer = function (msg, session, next) {
    serverStatusModel.lockGame(next);
};

/**
 * 解除锁定
 */
Handler.prototype.unLockServer = function (msg, session, next) {
    serverStatusModel.unLockGame(next);
};
